#include "thread.h"

int login(int netfd,sharInfo_t* sharInfo,MYSQL* mysql){
    train_t train;
    char sql[256];
    char userId[256];
    char passWd[256];
    int ret;
    while(1){
        int rret=recv(netfd,&train.length,sizeof(int),MSG_NOSIGNAL);
        if(rret==0){
            return -1;
        }
        
        recv(netfd,train.buf,train.length,MSG_NOSIGNAL);
        remove_trailing_invisible_chars(train.buf);

        strcpy(userId,train.buf);
        sprintf(sql,"select name from user where name = '%s';",userId);

        mysql_query(mysql,sql);
        MYSQL_RES *result=mysql_store_result(mysql);
        unsigned int rows=mysql_num_rows(result);
        if(rows==0){
            ret=-1;
            send(netfd,&ret,sizeof(int),MSG_NOSIGNAL);
            continue;
        }
        mysql_free_result(result);
        ret=0;
        send(netfd,&ret,sizeof(int),MSG_NOSIGNAL);
        bzero(&train,sizeof(train));
        recv(netfd,&train.length,sizeof(int),MSG_NOSIGNAL);
        recv(netfd,train.buf,train.length,MSG_NOSIGNAL);
        remove_trailing_invisible_chars(train.buf);

        strcpy(passWd,train.buf);
        bzero(sql,sizeof(sql));

        sprintf(sql,"select salt from user where name = '%s';",userId);
        mysql_query(mysql,sql);
        MYSQL_RES* salt_result=mysql_store_result(mysql);
        MYSQL_ROW row=mysql_fetch_row(salt_result);

        char *passwd=crypt(passWd,row[0]);
        
        bzero(sql,sizeof(sql));
        sprintf(sql,"select * from user where ciphertext = '%s'",passwd);
        mysql_query(mysql,sql);

        MYSQL_RES * cio_passWord=mysql_store_result(mysql);
        unsigned long realrow=mysql_num_rows(cio_passWord);
        if(realrow==0){
            ret =-1;
            send(netfd,&ret,sizeof(int),MSG_NOSIGNAL);
            continue;
        }
        
        mysql_free_result(cio_passWord);
        mysql_free_result(salt_result);
        break;
    }
    sharInfo->parentID=-1;
    sharInfo->lastID=-1;
    bzero(sql,sizeof(sql));

    sprintf(sql,"select ID from df_mes where user = '%s' and path = '/';",userId);
    mysql_query(mysql,sql);
    MYSQL_RES *result=mysql_store_result(mysql);
    MYSQL_ROW row=mysql_fetch_row(result);
    sharInfo->rootID=atoi(row[0]);
    printf("rootID = %d\n",sharInfo->rootID);
    memcpy(sharInfo->user,userId,strlen(userId));
    mysql_free_result(result);
    
    ret =0;
    send(netfd,&ret,sizeof(int),MSG_NOSIGNAL);

    return 0;
}
